<template>
  <div class="api-box">
    <slot :data="info" v-if="info" />
    <el-row type="flex" justify="center" v-if="errorMsg">
      <span class="error">{{ errorMsg }}</span>
    </el-row>
    <el-row type="flex" justify="center" align="center" class="loading-box" v-loading="isLoading" v-if="isLoading">
    </el-row>
  </div>
</template>

<script>
import { handleApi } from '../util';

export default {
  data() {
    return {
      isLoading: false,
      errorMsg: null,
      info: null,
    };
  },
  props: {
    autoRequest: {
      type: Boolean,
      default: true,
    },
    api: {
      type: [String, Object, Function],
      required: true,
    },
  },
  created() {
    if (this.autoRequest) {
      this.getInfo();
    }
  },
  methods: {
    getInfo() {
      this.isLoading = true;
      handleApi(this.api)
        .then(({ data }) => {
          this.info = data;
          this.errorMsg = '';
          this.$emit('result', data);
        })
        .catch((error) => {
          this.errorMsg = error.msg;
        })
        .finally(() => {
          setTimeout(() => {
            this.isLoading = false;
          }, 300);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.api-box {
  position: relative;
  .loading-box {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.7);
    top: 0;
    left: 0;
  }
  .error {
    color: #ff0000;
  }
}
</style>
